package com.kinyx.framework.db.sentence.res;

import com.kinyx.framework.db.configs.DBConfigs;
import com.kinyx.framework.db.vo.TableInfo;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

/**
 * 表子句
 */
@RequiredArgsConstructor // for resource
public class Table extends _Sentence {

	// from resource
	/** 实体类 */
	private final Class<?> entityClass;

	// from user
	/** 表索引值 */
	@Getter(value = AccessLevel.PACKAGE)
	private int tableIdx;

	// for subclass JoinTable
	// for subclass LinkTable
	// for this#idx
	Table(final Table table, final int tableIdx) {
		this.entityClass = table.entityClass;
		this.tableIdx = tableIdx;
	}

	@Override
	public String getSentence(final DBConfigs configs, final boolean isSQL, final boolean withTableAlias) {
		final TableInfo tableInfo = configs.getTableInfo(this.entityClass);
		final String tableName = isSQL ? tableInfo.getTableName() : tableInfo.getMappingClass().getSimpleName();
		if (withTableAlias) {
			return String.format("%s %s", tableName, Table.getTableAlias(tableInfo, this.tableIdx));
		}
		return tableName;
	}

	@Override
	public boolean equals(final Object obj) {
		if ((obj != null) && (obj instanceof Table)) {
			if (((Table) obj).entityClass.equals(this.entityClass)) {
				return true;
			}
		}
		return false;
	}

	private static String getTableAliasSuffix(final int tableIdx) { return (tableIdx > 0 ? String.valueOf(tableIdx) : ""); }
	private static String getTableAlias(final TableInfo tableInfo, final int tableIdx) { return tableInfo.getTableAlias() + getTableAliasSuffix(tableIdx); }
	// for Column.getSentence
	static String getTableAlias(final DBConfigs configs, final Class<?> entityClass, final int tableIdx) { return getTableAlias(configs.getTableInfo(entityClass), tableIdx); }
	// for KSELECT.getSentence
	String getTableAlias(final DBConfigs configs) { return Table.getTableAlias(configs.getTableInfo(this.entityClass), this.tableIdx); }

	public Table idx(final int tableIdx) { return new Table(this, tableIdx); }

}
